﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using DSA.Shopping_List_Menu;

namespace DSA
{
    public partial class PivotPage1 : PhoneApplicationPage
    {
        public class shoppingListEntry
        {
            string name;
            string quantity;
            string price;
            bool check;
            string imgSource;

            public string Name { get { return name; } set { name = value; } }
            public string Quantity { get { return quantity; } set { quantity = value; } }
            public string Price { get { return price; } set { price = value; } }
            public bool Checked { get { return check; } set { check = value; } }
            public string ImageSource { get { return imgSource; } set { imgSource = value; } }
        }

        private string listname;

        public PivotPage1()
        {
            InitializeComponent();

            listname = "";

            // DONT LOAD HERE, LOAD ON NAVIGATE TO
            //LoadFromIsolatedStorage();

            // Offers List Init
            for (int i = 0; i < 3; i++)
            {
                OfferListEntry item = new OfferListEntry();
                item.txtProduct.Text = "Mahou 6-pack";
                item.txtDesc.Text = "Oferta exclusiva Carrefour.";
                item.txtPrice.Text = "$5.99";
                item.imgOffer.Source = new BitmapImage(new Uri("/res/Duff-Beer-Six-Pack.jpg", UriKind.Relative));
                item.ImageSource = "/res/Duff-Beer-Six-Pack.jpg";
                listBoxOffers.Items.Add(item);
            }
        }

        private void LoadFromIsolatedStorage()
        {
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("shopping_lists" + listname + ".xml", FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<shoppingListEntry>));
                        List<shoppingListEntry> data = (List<shoppingListEntry>)serializer.Deserialize(stream);

                        int count = 0;
                        foreach (shoppingListEntry item in data)
                        {
                            count++;
                            Color color = new Color();
                            color.A = 255;
                            switch (count)
                            {
                                case 1:
                                    color.R = 150;
                                    color.G = 247;
                                    color.B = 152;
                                    break;
                                case 2:
                                    color.R = 248;
                                    color.G = 203;
                                    color.B = 60;
                                    break;
                                case 3:
                                    color.R = 203;
                                    color.G = 204;
                                    color.B = 252;
                                    
                                    break;
                                case 4:
                                    color.R = 117;
                                    color.G = 249;
                                    color.B = 254;
                                    break;
                                default:
                                    color.R = 255;
                                    color.G = 14;
                                    color.B = 14;
                                    break;
                            }

                            ListEntryItem entry = new ListEntryItem();

                            entry.chkItemName.IsChecked = item.Checked;
                            entry.txtName.Text = item.Name;
                            entry.txtPrice.Text = item.Price;
                            entry.txtQuantity.Text = item.Quantity;
                            //entry.rectangle1.Fill = new SolidColorBrush(color);
                            entry.ImageSource = item.ImageSource;
                            entry.image.Source = new BitmapImage(new Uri(item.ImageSource, UriKind.Relative));

                            listboxItemList.Items.Add(entry);

                            MapListItem i = new MapListItem();
                            i.txtName.Text = item.Name;
                            i.ColorRect.Fill = new SolidColorBrush(color);
                            i.ImageSource = item.ImageSource;
                            i.image.Source = new BitmapImage(new Uri(item.ImageSource, UriKind.Relative));
                            listBoxMap.Items.Add(i);
                        }
                    }
                }
            }
            catch
            {
                //add some code here
            }
        }

        private void SaveToIsolatedStorage()
        {
            // Write to the Isolated Storage
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = true;

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("shopping_lists" + listname+ ".xml", FileMode.Create))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<shoppingListEntry>));
                    using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                    {
                        List<shoppingListEntry> save_list = new List<shoppingListEntry>();
                        for (int i = 0; i < listboxItemList.Items.Count; i++)
                        {
                            ListEntryItem temp = (ListEntryItem)listboxItemList.Items[i];
                            shoppingListEntry a = new shoppingListEntry();
                            a.Name = temp.txtName.Text;
                            a.Price = temp.txtPrice.Text;
                            a.Quantity = temp.txtQuantity.Text;
                            a.ImageSource = temp.ImageSource;

                            if (temp.chkItemName.IsChecked != null)
                            {
                                if (temp.chkItemName.IsChecked == true)
                                    a.Checked = true;
                            }
                            else
                                a.Checked = false;

                            //img?

                            save_list.Add(a);
                        }
                        serializer.Serialize(xmlWriter, save_list);
                    }
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // SAVE TO XML OR SOMETHING
            SaveToIsolatedStorage();

            // Navigate to main menu, not last screen
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (this.NavigationContext.QueryString.ContainsKey("list"))
            {
                listname = this.NavigationContext.QueryString["list"];
            }

            listboxItemList.Items.Clear();
            LoadFromIsolatedStorage();

            if (this.NavigationContext.QueryString.ContainsKey("name"))
            {
                string name = this.NavigationContext.QueryString["name"];
                string quant = "1";
                string price = "$0.00";
                string imgsource = "/res/question.png";
                string check = "false";

                if (this.NavigationContext.QueryString.ContainsKey("quant"))
                {
                    quant = this.NavigationContext.QueryString["quant"];
                }

                if (this.NavigationContext.QueryString.ContainsKey("price"))
                {
                    price = this.NavigationContext.QueryString["price"];
                }

                if (this.NavigationContext.QueryString.ContainsKey("imgsource"))
                {
                    imgsource = this.NavigationContext.QueryString["imgsource"];
                }

                if (this.NavigationContext.QueryString.ContainsKey("checked"))
                {
                    check = this.NavigationContext.QueryString["checked"];
                }

                ListEntryItem item = new ListEntryItem();
                item.chkItemName.IsChecked = Convert.ToBoolean(check);
                item.txtName.Text = name;
                item.txtPrice.Text = price;
                item.txtQuantity.Text = "x" + quant;
                item.image.Source = new BitmapImage(new Uri(imgsource, UriKind.Relative));
                item.ImageSource = imgsource;
                listboxItemList.Items.Add(item);
            }

            SaveToIsolatedStorage();

            // Update labels
            listboxItemList_Tap(null, null);

            base.OnNavigatedTo(e);
        }

        private void AddClick(object sender, EventArgs e)
        {
            SaveToIsolatedStorage();
            NavigationService.Navigate(new Uri("/Shopping List Menu/AddItemPage.xaml?list=" + listname, UriKind.Relative));
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string pivotResource;

            switch (_pivot.SelectedIndex)
            {
                case 0:
                    pivotResource = "addAppBar";
                    break;

                case 1:
                    // change map
                    image1.Source = new BitmapImage(new Uri("/res/maps/map_" + (listboxItemList.Items.Count < 6 ? listboxItemList.Items.Count.ToString() : "5") + ".png", UriKind.Relative));
                    pivotResource = "defaultAppBar";
                    break;

                default:
                    pivotResource = "defaultAppBar";
                    break;
            }

            ApplicationBar = (ApplicationBar)Resources[pivotResource]; 

            // Calculate total and items labels
            listboxItemList_Tap(null, null);
        }

        public void listboxItemList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // Change the total
            double total = 0;
            bool final = true;
            for (int i = 0; i < listboxItemList.Items.Count; i++)
            {
                ListEntryItem item = (ListEntryItem)listboxItemList.Items[i];
                if (item.chkItemName.IsChecked == false)
                {
                    final = false;
                }
                else
                {
                    total += Convert.ToDouble(item.txtPrice.Text.Replace("$", "")) * Convert.ToDouble(item.txtQuantity.Text.Replace("x", ""));
                }
            }

            txtTotal.Text = "Total: $" + total;
            if (!final)
                txtTotal.Foreground = new SolidColorBrush(Colors.Red);
            else
                txtTotal.Foreground = new SolidColorBrush(Colors.White);

            // Update number of items
            txtItems.Text = "Items: " + listboxItemList.Items.Count;

            // update map list
            listBoxMap.Items.Clear();
            int count = 0;
            foreach (ListEntryItem item in listboxItemList.Items)
            {
                count++;
                Color color = new Color();
                color.A = 255;
                switch (count)
                {
                    case 1:
                        color.R = 150;
                        color.G = 247;
                        color.B = 152;
                        break;
                    case 2:
                        color.R = 248;
                        color.G = 203;
                        color.B = 60;
                        break;
                    case 3:
                        color.R = 203;
                        color.G = 204;
                        color.B = 252;
                                    
                        break;
                    case 4:
                        color.R = 117;
                        color.G = 249;
                        color.B = 254;
                        break;
                    default:
                        color.R = 255;
                        color.G = 14;
                        color.B = 14;
                        break;
                }

                MapListItem i = new MapListItem();
                i.txtName.Text = item.txtName.Text;
                i.ColorRect.Fill = new SolidColorBrush(color);
                i.ImageSource = item.ImageSource;
                i.image.Source = new BitmapImage(new Uri(item.ImageSource, UriKind.Relative));
                listBoxMap.Items.Add(i);
            }
        }

        private void ScannerClick(object sender, EventArgs e)
        {
            SaveToIsolatedStorage();
            NavigationService.Navigate(new Uri("/ItemScan/ScanItemPage.xaml?list=" + listname, UriKind.Relative));
        }

        private void CheckoutClick(object sender, EventArgs e)
        {
            SaveToIsolatedStorage();
            NavigationService.Navigate(new Uri("/Checkout/CheckoutPage.xaml?list=" + listname, UriKind.Relative));
        }

        private void listBoxMap_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (image1.Visibility == System.Windows.Visibility.Collapsed)
            {
                image1.Visibility = System.Windows.Visibility.Visible;
                textBlock1.Text = "Tap to see the list of items.";
            }
            else
            {
                image1.Visibility = System.Windows.Visibility.Collapsed;
                textBlock1.Text = "Tap to see the map.";
            }
        }
    }
}